/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/Data/Rel/SqlDelayThread.h"
#include <memory>
#include <mysql.h>
#include "Ucop/Data/Rel/SqlOperation.h"
#include "Ucop/Data/Rel/SqlConnection.h"
using Ucop::System::Thread;

/* Delay thread sleep time */
#define SQLTHREAD_SLEEPTIME  10
/* Async sql connection ping interval */
#define SQLCONN_PING_INTERVAL	60000


namespace Ucop {
namespace Data {
namespace Rel {

    SqlDelayThread::SqlDelayThread(Session* _Sess, SqlConnection* _Conn)
        : _MysqlQueue()
        , _Mysess(_Sess)
        , _Myconn(_Conn)
        , _Myrunning(true)
        , _Mythread(this)
        , _MystartEvent()
    {
    }

    SqlDelayThread::~SqlDelayThread(void)
    {
        _ProcessRequests();
    }

    void SqlDelayThread::Run(void)
    {
        _MystartEvent.Set();

        mysql_thread_init();
		static int _ConnPingTime = 0;
        while (_Myrunning)
        {
            Thread::Sleep(SQLTHREAD_SLEEPTIME);
            _ProcessRequests();
			/* Ping */
			_ConnPingTime += SQLTHREAD_SLEEPTIME;
			if (_ConnPingTime >= SQLCONN_PING_INTERVAL) {
				_ConnPingTime = 0;
				_Myconn->Ping();
			}
        }
        mysql_thread_end();
    }

    bool SqlDelayThread::Start(void)
    {
        if (_Mythread.Start()) {
            _MystartEvent.Wait();
            return true;
        }
        return false;
    }

    void SqlDelayThread::Stop(void)
    {
        _Myrunning = false;
        _Mythread.Join();
    }

    void SqlDelayThread::_ProcessRequests(void)
    {
        SqlOperation* _Op = NULL;
        while (_MysqlQueue.Next(_Op))
        {
            std::auto_ptr<SqlOperation> _OpPtr(_Op);
            _OpPtr->Execute(_Myconn);
        }
    }

}}}